package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	stream "grpc/stream_grpc_test/proto"
	"sync"
	"time"
)

func main() {
	dial, err := grpc.Dial("127.0.0.1:8088", grpc.WithInsecure()) // 连接服务
	if err != nil {
		panic(err)
	}
	defer dial.Close()

	c := stream.NewGreeterClient(dial)
	////服务端流模式调用
	//getStream, _ := c.GetStream(context.Background(), &stream.StreamReqData{Data: "test"})
	//for true {
	//	recv, err := getStream.Recv()
	//	if err != nil {
	//		break
	//	}
	//
	//	fmt.Println(recv.Data)
	//}

	// 客户端流模式
	//rand.Seed(time.Now().UnixNano())
	//putStream, _ := c.PutStream(context.Background())
	//i := 0
	//for {
	//	err := putStream.Send(&stream.StreamReqData{Data: fmt.Sprintf("上报：经度：%d - 纬度：%d", rand.Intn(200), rand.Intn(4000))})
	//	if err != nil {
	//		fmt.Println(err)
	//		break
	//	}
	//	time.Sleep(time.Second)
	//
	//	if i > 10 {
	//		break
	//	}
	//	i++
	//}

	//双向模式
	allStr, err := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			recv, _ := allStr.Recv()
			fmt.Println("收到服务端消息:", recv.Data)
		}
	}()

	go func() {
		defer wg.Done()
		for {
			_ = allStr.Send(&stream.StreamReqData{Data: "我是客户端"})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()
}
